<template>
  <div class="container">
    <el-dialog :title="isEdit ? '修改文章' : '新增文章'" :visible="showDialog" width="35%" @close="handleClose">
      <el-form label-width="100px" :model="formData" ref="formDataRef" :rules="rules">
        <el-form-item label="文章标题:" prop="title">
          <el-input placeholder="请输入文章标题" v-model="formData.title"></el-input>
        </el-form-item>
        <el-form-item label="文章内容:" prop="articleBody">
          <quill-editor
            :options="editorOption"
            v-model="formData.articleBody"
            ref="myQuillEditor"
            class="editor"
            @blur="articleBodyBlur"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="视频地址:">
          <el-input placeholder="请输入视频地址" v-model="formData.videoURL"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button type="primary" @click="enterFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    // 显示对话框
    showDialog: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      // 表单数据
      formData: {
        title: '', // 文章标题
        articleBody: '', // 文章正文
        videoURL: '' // 视频地址
      },
      // 富文本配置
      editorOption: {
        // 富文本编辑器配置
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image'], // 上传图片
            ['link'] // 链接
          ]
        }
      },
      // 校验规则
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章正文' }]
      }
    }
  },
  methods: {
    // 自定义触发校验
    articleBodyBlur () {
      this.$refs.formDataRef.validateField('articleBody')
    },
    // 关闭对话框
    handleClose () {
      this.cancelFn()
    },
    // 取消
    cancelFn () {
      this.$emit('update:showDialog', false)
      this.formData = {
        title: '', // 文章标题
        articleBody: '', // 文章正文
        videoURL: '' // 视频地址
      }
      this.$refs.formDataRef.resetFields()
    },
    // 确认
    enterFn () {
      this.$refs.formDataRef.validate(valid => {
        if (!valid) return
        this.$emit('addOrEdit', { ...this.formData })
        this.cancelFn()
      })
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .quill-editor {
  .ql-container {
    height: 200px;
  }
  .ql-toolbar {
    padding: 0 8px;
  }
  .ql-toolbar.ql-snow .ql-formats {
    margin-right: 0;
  }
}
</style>
